import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useAppStore } from '@/store';

axios.defaults.baseURL = import.meta.env.VITE_APP_BASE_API;

const whitePath = ['/login']; // 白名单

// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    const appStore = useAppStore();
    if (appStore.token) {
      config.headers.Authorization = 'Bearer ' + appStore.token; // 加Bearer前缀 是express-token规范
    } else {
      const requstUrl = config.url.replace(
        import.meta.env.VITE_APP_BASE_API,
        '',
      );
      if (!whitePath.includes(requstUrl)) {
        ElMessage({
          message: '登录失效，请重新登录！',
          type: 'error',
        });
        location.href = '/login';
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    const { data: rep } = response;
    if (!rep.code) {
      ElMessage.error(rep.msg);
      throw new Error(rep.msg);
    }
    return rep.data;
  },
  (error) => {
    const appStore = useAppStore();
    console.log(error);
    if (error.response.status === 401) {
      ElMessage.error('登陆失效,请重新登陆');
      appStore.logout();
      return Promise.reject(error);
    }
    ElMessage.error(error.message);
    return Promise.reject(error);
  },
);
